﻿
using ChoJuRating.View;
using ChongJu.CloudService;
using Public.Logger;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using Tasks = System.Threading.Tasks.Task;

namespace ChoJu.Single.Views
{
    /// <summary>
    /// APPUpdateView.xaml 的交互逻辑
    /// </summary>
    public partial class APPUpdateView : Window
    {
        private string targetVersion;
        private bool _isCancel = false;
        private CloudService _cloud;
        private string _dir = Path.Combine(AppContext.BaseDirectory, "Version");


        public bool IsUpdate;

        public APPUpdateView(string currentVersion, string targetVersion)
        {
            InitializeComponent();

            _cloud = new CloudService();
            this.targetVersion = targetVersion;
            tbkCurrent.Text = currentVersion;
            tbkUpdate.Text = targetVersion;

            Init(); //一有更新自动下载
        }

        private async void Init()
        {
            string filePath = null;
            try
            {
                btnSure.Content = "下载中……";
                filePath = await Tasks.Factory.StartNew(() => _cloud.DownloadSystemVersion(targetVersion));
                if (string.IsNullOrWhiteSpace(filePath) == true || filePath.Contains("404") == true)
                {
                    CJMsgBox.ShowDialog("下载升级包异常失败", MsgTitle.Error);
                    Close();
                    return;
                }
            }
            catch (Exception ex)
            {
                CJMsgBox.ShowDialog("下载升级包异常：" + ex.Message, MsgTitle.Error);
                Close();
                return;
            }

            if (_isCancel == true)
                return;

            //减压 压缩包
            btnSure.Content = "减压中……";
            try
            {
                string strCurrentExePath = AppDomain.CurrentDomain.BaseDirectory;
                string strUpdateExeName = "ChoJuUpdater.exe";
                var allUpPr = Process.GetProcessesByName("ChoJuUpdater").ToList();
                if (allUpPr.Count > 0)
                {
                    allUpPr.ForEach(q => q.Kill());
                    System.Threading.Thread.Sleep(2000);
                }

                string strNewExeDirPath = Path.Combine(_dir, Path.GetFileNameWithoutExtension(filePath));
                if (Directory.Exists(strNewExeDirPath))
                    Directory.Delete(strNewExeDirPath, true);

                Directory.CreateDirectory(strNewExeDirPath);
                ZipFile.ExtractToDirectory(filePath, strNewExeDirPath);

                var strFileArray = Directory.GetFiles(strNewExeDirPath).ToList();
                var update = strFileArray.Find(q => q.EndsWith(strUpdateExeName));
                if (update == null)
                {
                    CJMsgBox.ShowDialog("升级App不存在！", MsgTitle.Error);
                    Close();
                    return;
                }
                else
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.FileName = update; //启动的应用程序名称
                    Process.Start(startInfo);
                    Environment.Exit(0);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("升级过程中发生异常", ex);
                CJMsgBox.ShowDialog("升级过程中发生异常：" + ex.Message, MsgTitle.Error);
            }

            btnSure.Content = "开始升级";
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            _isCancel = true;
            IsUpdate = false;
            this.DialogResult = false;
        }

        private void btnSure_Click(object sender, RoutedEventArgs e)
        {
            IsUpdate = true;
            //pgbLoad.IsIndeterminate = true;
            Init();
        }
    }
}
